﻿namespace Atomic.Events
{
    using System.Linq;
    using System.Collections.Generic;
    using System.Collections.Concurrent;

    using Atomic.Events.Queues;

    /// <summary>
    /// 事件管理器基类
    /// </summary>
    /// <typeparam name="TEvent">事件类型</typeparam>
    public abstract class EventManagerBase<TEvent> : IEventManager<TEvent> where TEvent : IEvent
    {
        /// <summary>
        /// 事件处理器组。
        /// </summary>
        protected IEventHandlerGroup<TEvent> _eventHandlerGroup = null;

        /// <summary>
        /// 初始化事件管理器。
        /// </summary>
        public EventManagerBase()
        {
            this._eventHandlerGroup = this.CreateEventHandlers();
        }

        /// <summary>
        /// 填充事件处理器。
        /// </summary>
        /// <param name="eventHandlers">事件处理器</param>
        /// <returns>事件处理器组</returns>
        public IEventHandlerGroup<TEvent> EventHandlersWith(params IEventHandler<TEvent>[] eventHandlers)
        {
            return this._eventHandlerGroup.EventHandlersWith(eventHandlers);
        }

        /// <summary>
        /// 清理事件处理器。
        /// </summary>
        public void Clear()
        {
            this._eventHandlerGroup.Clear();
        }

        /// <summary>
        /// 创建事件处理器。
        /// </summary>
        /// <param name="eventHandlers">事件处理器数组</param>
        /// <returns>事件处理器组</returns>
        internal IEventHandlerGroup<TEvent> CreateEventHandlers(params IEventHandler<TEvent>[] eventHandlers)
        {
            if (this._eventHandlerGroup == null)
            {
                this._eventHandlerGroup = new EventHandlerGroup<TEvent>(eventHandlers);
            }
            else
            {
                this._eventHandlerGroup.EventHandlersWith(eventHandlers);
            }

            return this._eventHandlerGroup;
        }

        /// <summary>
        /// 发布事件。
        /// </summary>
        /// <param name="_event">事件信息</param>
        public abstract void Publish(TEvent _event);
    }
}